var memberPointsServiceNative = require("../services/MemberPointsService");
var async = require("async");
var moment = require("moment");
var dates = require("../common/dates");
var errorHandler = require('../common/errorHandler');
var MemberPointsController = {
		pointsList: function (req, res, next) {
		    var memberPointsService = errorHandler.errorToResponse(req, res, memberPointsServiceNative);
			var memberId = req.params.id;
			var type = req.query.type;
			var allType = ['reward', 'manual-update', 'refund', 'pay', 'revert'];
			if (type == "pay") {
				allType = ['refund', 'pay'];
			} else if (type == "add") {
				allType = ['reward', 'manual-update', 'revert'];
			}
			var month = req.query.month;
			if (!month) {
				month = moment().format("YYYY-MM");
			}
			var resultData = {};


			async.series([
					function (cb) {
						memberPointsService.getPoints(memberId, function (err, points) {
							if (!points) {
								points = {points: 0}
							}
							resultData.points = points;
							cb(err, points);
						})
					},
					function (cb) {
						var types = ['reward', 'manual-update', 'revert'];
						memberPointsService.getPointsTotal(memberId, types, function (err, total) {
							resultData.pointsTotalAdd = total;
							cb(err, total);
						})
					},
					function (cb) {
						var types = ['refund', 'pay'];
						memberPointsService.getPointsTotal(memberId, types, function (err, total) {
							resultData.pointsTotalPay = total;
							cb(err, total);
						})
					},
					function (cb) {
						memberPointsService.getPointsTxList(memberId, allType, dates.monthStart(month, 2), dates.monthEnd(dates.monthStart(month, 0)), function (err, txList) {
							resultData.txList = txList;
							resultData.count = txList.length;
							cb(err, txList);
						})
					}
				],
				function (err, result) {
					res.send(resultData);
				})
		},
		getOnePointsTx: function (req, res, next) {
		    var memberPointsService = errorHandler.errorToResponse(req, res, memberPointsServiceNative);

			var txId = req.params.id;
			memberPointsService.getPointsOneTx(txId, function (err, tx) {
				if (err) {
					return res.status(400).json({error: "参数错误"});
				}
				res.send(tx);
			})
		}
	}
	;

module.exports = MemberPointsController;